package com.alex.seo.service.publishing;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

import redstone.xmlrpc.XmlRpcException;

import com.alex.seo.contentsource.dto.ContentDTO;
import com.alex.seo.dao.page.PageDao;
import com.alex.seo.dao.site.SiteDao;
import com.alex.seo.domain.page.Page;
import com.alex.seo.domain.site.Site;
import com.alex.seo.service.logging.LogType;
import com.alex.seo.service.logging.LoggingService;
import com.alex.seo.service.sitebridge.SiteBridge;
import com.alex.seo.service.sitebridge.SiteBridgeException;
import com.alex.seo.service.sitebridge.SiteBridgeLookupException;
import com.alex.seo.service.sitebridge.SiteBridgeLookupService;
import com.alex.seo.service.sitebridge.dto.PageDTO;

@Transactional
public class PublishingServiceBean implements PublishingService {
	
	private LoggingService loggingService;

	private SiteDao siteDao;
	
	private PageDao pageDao;
	
	@Required
	public void setLoggingService(LoggingService loggingService) {
		this.loggingService = loggingService;
	}
	
	@Required
	public void setSiteDao(SiteDao siteDao) {
		this.siteDao = siteDao;
	}
	
	@Required
	public void setPageDao(PageDao pageDao) {
		this.pageDao = pageDao;
	}

	@Override
	public void createPost(Integer siteId, ContentDTO contentDTO) throws PublishingServiceException {
		try {
			Site site = siteDao.get(siteId, false);
			SiteBridge siteAPI = SiteBridgeLookupService.lookup(site);
			PageDTO pageDTO = siteAPI.createPost(contentDTO);
			
			Page page = new Page(pageDTO.getId(), pageDTO.getUrl(), site);
			pageDao.persist(page);
			
			loggingService.logEvent(LogType.PAGE_CREATED, page.toString());
			
		} catch (SiteBridgeLookupException | SiteBridgeException | XmlRpcException e) {
			throw new PublishingServiceException(e);
		}
	}

}
